<?php

Raise::load('control.RaiseContentArea');
Raise::load('core.net.http.RaiseHttpRequest');

/**
 * RaiseAjaxArea UIControl class
 * An area that is capable of being updated via AJAX calls.
 *
 * @author Sam-Mauris Yong / hellclanner at live dot com
 * @license http://www.opensource.org/licenses/bsd-license New BSD License
 * @package phpraise.control
 * @since 1.2
 */
abstract class RaiseAjaxArea extends RaiseContentArea {

    /**
     * Flag that determines whether this is in AJAX mode or not
     * @var boolean
     */
    private $isAjax = false;

    /**
     * Construct the RaiseAjaxArea object
     */
    function __construct(){
        parent::__construct('');
    }
    
    /**
     * Get or set whether this is an AJAX request or not
     * @param boolean $i (optional) Set the value
     * @return boolean
     */
    public function isAjax($i = null){
        if(func_num_args() == 1){
            $this->isAjax = $i;
        }
        return $this->isAjax;
    }

    /**
     * Return the final output of the control
     * @return string
     */
    function output(){
        if($this->isAjax){
            $this->template('$content$');
        }
        $c = $this->clientId();
        if(!$c){
            throw new RaiseInvalidRequestException('Cannot output RaiseAjaxArea: RaiseAjaxArea needs to have a fixed Client ID to uniquely identify itself on AJAX requests.');
        }
        $o = parent::output();
        if($this->isAjax){
            $o = 'if(!phpRaise){alert(\'Error CE01\');}phpRaise.ajaxCallback(\'' . $c . '\', \'' . str_replace(array('\\', '\''), array('\\\\', '\\\''), $o) . '\');';
        }
        return $o;
    }

    /**
     * Gets the URL to update this AJAX area on the current page
     * @param RaiseCollection $params Additional parameters to pass to RaiseAjaxArea control
     * @return RaiseUrl
     */
    function staticLink($params = array()){
        $request = RaiseHttpRequest::loadCurrent();
        $url = $request->url();
        $url->params()->append($params);
        return $url;
    }

    /**
     * Gets the AJAX Javascript that will call the AJAX controller with specific parameters
     * @param array $params Additional parameters to pass to RaiseAjaxArea control
     * @return string The Javascript Code
     */
    function ajaxJavascript($params = array()){
        $request = RaiseHttpRequest::loadCurrent();
        $url = $request->url();
        $url->params()->append($params);
        $c = $this->clientId;
        $url->params()->add('ajaxcaller', $c);
        
        return 'if(!phpRaise){alert(\'Error CE01\');}phpRaise.ajaxCall(\'' . $c . '\', \'' . $url->__toString() . '\');return false;';
    }

}